// main.js
const { app, BrowserWindow, globalShortcut, ipcMain  } = require('electron')
const fs = require('fs');
const path = require('path')
let mainWindow
let shortcutRegistered = false;

function createWindow () {
   // 读取配置文件
  const configPath = path.join("res/", 'config.json');
  const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
  mainWindow = new BrowserWindow({
    // width: 800,
    // height: 600,
    fullscreen: true,
    autoHideMenuBar: true, // 设置菜单栏自动隐藏
    skipTaskbar: true, // 设置窗口不显示在任务栏上
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      preload: path.join(__dirname, 'preload.js'),
  },
    alwaysOnTop: true, // 设置窗口始终位于顶层
  })
  console.log(config.url);
  // 加载外部网站
  mainWindow.loadURL(config.url)

  // 注册全局快捷键
  // registerGlobalShortcuts()

  mainWindow.on('closed', function () {
    mainWindow = null
  })
  mainWindow.setMenu(null); 

  // 监听来自渲染进程的消息
  ipcMain.on('close-app', (event) => {
    globalShortcut.unregister('CommandOrControl+Shift+H');
    app.quit(); // 退出整个应用
  });

  // 注册快捷键
  if (!shortcutRegistered) {
    globalShortcut.register('CommandOrControl+Shift+H', () => {
      globalShortcut.unregister('CommandOrControl+Shift+H');
      app.quit(); // 当按下快捷键时关闭程序
    });

    shortcutRegistered = true;
  }
}

function registerGlobalShortcuts() {
  // 注册全局快捷键
  const isRegisteredCtrlShiftI = globalShortcut.register('CommandOrControl+Shift+I', () => {
    console.log('Ctrl+Shift+I is disabled');
  });

  const isRegisteredF12 = globalShortcut.register('F12', () => {
    console.log('F12 is disabled');
  });

  if (!isRegisteredCtrlShiftI || !isRegisteredF12) {
    console.error('Failed to register one or more global shortcuts.');
  }

  // 当应用关闭时，注销所有全局快捷键
  app.on('before-quit', () => {
    globalShortcut.unregisterAll();
  });
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    globalShortcut.unregister('CommandOrControl+Shift+H');
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})